3 * @defgroup FileBackend File backend
6 * File backend is used to interact with file storage systems,
7 * such as the local file system, NFS, or cloud storage systems.
11 * Base class for all file backends.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
29 * @ingroup FileBackend
30 * @author Aaron Schulz
34 * @brief Base class for all file backend classes (including multi-write backends).
36 * This class defines the methods as abstract that subclasses must implement.
37 * Outside callers can assume that all backends will have these functions.
39 * All "storage paths" are of the format "mwstore://<backend>/<container>/<path>".
40 * The "<path>" portion is a relative path that uses UNIX file system (FS)
41 * notation, though any particular backend may not actually be using a local
43 * Therefore, the relative paths are only virtual.
45 * Backend contents are stored under wiki-specific container names by default.
46 * For legacy reasons, this has no effect for the FS backend class, and per-wiki
47 * segregation must be done by setting the container paths appropriately.
49 * FS-based backends are somewhat more restrictive due to the existence of real
50 * directory files; a regular file cannot have the same name as a directory. Other
51 * backends with virtual directories may not have this limitation. Callers should
52 * store files in such a way that no files and directories are under the same path.
54 * Methods should avoid throwing exceptions at all costs.
55 * As a corollary, external dependencies should be kept to a minimum.
57 * @ingroup FileBackend
60 abstract class FileBackend
{
61 protected $name; // string; unique backend name
62 protected $wikiId; // string; unique wiki name
63 protected $readOnly; // string; read-only explanation message
64 protected $parallelize; // string; when to do operations in parallel
65 protected $concurrency; // integer; how many operations can be done in parallel
67 /** @var LockManager */
68 protected $lockManager;
69 /** @var FileJournal */
70 protected $fileJournal;
73 * Create a new backend instance from configuration.
74 * This should only be called from within FileBackendGroup.
77 * - name : The unique name of this backend.
78 * This should consist of alphanumberic, '-', and '_' characters.
79 * This name should not be changed after use.
80 * - wikiId : Prefix to container names that is unique to this wiki.
81 * It should only consist of alphanumberic, '-', and '_' characters.
82 * - lockManager : Registered name of a file lock manager to use.
83 * - fileJournal : File journal configuration; see FileJournal::factory().
84 * Journals simply log changes to files stored in the backend.
85 * - readOnly : Write operations are disallowed if this is a non-empty string.
86 * It should be an explanation for the backend being read-only.
87 * - parallelize : When to do file operations in parallel (when possible).
88 * Allowed values are "implicit", "explicit" and "off".
89 * - concurrency : How many file operations can be done in parallel.
91 * @param $config Array
94 public function __construct( array $config ) {
95 $this->name
= $config['name'];
96 if ( !preg_match( '!^[a-zA-Z0-9-_]{1,255}$!', $this->name
) ) {
97 throw new MWException( "Backend name `{$this->name}` is invalid." );
99 $this->wikiId
= isset( $config['wikiId'] )
101 : wfWikiID(); // e.g. "my_wiki-en_"
102 $this->lockManager
= ( $config['lockManager'] instanceof LockManager
)
103 ?
$config['lockManager']
104 : LockManagerGroup
::singleton()->get( $config['lockManager'] );
105 $this->fileJournal
= isset( $config['fileJournal'] )
106 ?
( ( $config['fileJournal'] instanceof FileJournal
)
107 ?
$config['fileJournal']
108 : FileJournal
::factory( $config['fileJournal'], $this->name
) )
109 : FileJournal
::factory( array( 'class' => 'NullFileJournal' ), $this->name
);
110 $this->readOnly
= isset( $config['readOnly'] )
111 ?
(string)$config['readOnly']
113 $this->parallelize
= isset( $config['parallelize'] )
114 ?
(string)$config['parallelize']
116 $this->concurrency
= isset( $config['concurrency'] )
117 ?
(int)$config['concurrency']
122 * Get the unique backend name.
123 * We may have multiple different backends of the same type.
124 * For example, we can have two Swift backends using different proxies.
128 final public function getName() {
133 * Check if this backend is read-only
137 final public function isReadOnly() {
138 return ( $this->readOnly
!= '' );
142 * Get an explanatory message if this backend is read-only
144 * @return string|bool Returns false if the backend is not read-only
146 final public function getReadOnlyReason() {
147 return ( $this->readOnly
!= '' ) ?
$this->readOnly
: false;
151 * This is the main entry point into the backend for write operations.
152 * Callers supply an ordered list of operations to perform as a transaction.
153 * Files will be locked, the stat cache cleared, and then the operations attempted.
154 * If any serious errors occur, all attempted operations will be rolled back.
156 * $ops is an array of arrays. The outer array holds a list of operations.
157 * Each inner array is a set of key value pairs that specify an operation.
159 * Supported operations and their parameters. The supported actions are:
167 * a) Create a new file in storage with the contents of a string
171 * 'dst' => <storage path>,
172 * 'content' => <string of new file contents>,
173 * 'overwrite' => <boolean>,
174 * 'overwriteSame' => <boolean>
178 * b) Copy a file system file into storage
182 * 'src' => <file system path>,
183 * 'dst' => <storage path>,
184 * 'overwrite' => <boolean>,
185 * 'overwriteSame' => <boolean>
189 * c) Copy a file within storage
193 * 'src' => <storage path>,
194 * 'dst' => <storage path>,
195 * 'overwrite' => <boolean>,
196 * 'overwriteSame' => <boolean>
200 * d) Move a file within storage
204 * 'src' => <storage path>,
205 * 'dst' => <storage path>,
206 * 'overwrite' => <boolean>,
207 * 'overwriteSame' => <boolean>
211 * e) Delete a file within storage
215 * 'src' => <storage path>,
216 * 'ignoreMissingSource' => <boolean>
220 * f) Do nothing (no-op)
227 * Boolean flags for operations (operation-specific):
228 * - ignoreMissingSource : The operation will simply succeed and do
229 * nothing if the source file does not exist.
230 * - overwrite : Any destination file will be overwritten.
231 * - overwriteSame : An error will not be given if a file already
232 * exists at the destination that has the same
233 * contents as the new contents to be written there.
235 * $opts is an associative of boolean flags, including:
236 * - force : Operation precondition errors no longer trigger an abort.
237 * Any remaining operations are still attempted. Unexpected
238 * failures may still cause remaning operations to be aborted.
239 * - nonLocking : No locks are acquired for the operations.
240 * This can increase performance for non-critical writes.
241 * This has no effect unless the 'force' flag is set.
242 * - allowStale : Don't require the latest available data.
243 * This can increase performance for non-critical writes.
244 * This has no effect unless the 'force' flag is set.
245 * - nonJournaled : Don't log this operation batch in the file journal.
246 * This limits the ability of recovery scripts.
247 * - parallelize : Try to do operations in parallel when possible.
248 * - bypassReadOnly : Allow writes in read-only mode (since 1.20).
250 * @remarks Remarks on locking:
251 * File system paths given to operations should refer to files that are
252 * already locked or otherwise safe from modification from other processes.
253 * Normally these files will be new temp files, which should be adequate.
257 * This returns a Status, which contains all warnings and fatals that occured
258 * during the operation. The 'failCount', 'successCount', and 'success' members
259 * will reflect each operation attempted.
261 * The status will be "OK" unless:
262 * - a) unexpected operation errors occurred (network partitions, disk full...)
263 * - b) significant operation errors occured and 'force' was not set
265 * @param $ops Array List of operations to execute in order
266 * @param $opts Array Batch operation options
269 final public function doOperations( array $ops, array $opts = array() ) {
270 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
271 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
273 if ( empty( $opts['force'] ) ) { // sanity
274 unset( $opts['nonLocking'] );
275 unset( $opts['allowStale'] );
277 $opts['concurrency'] = 1; // off
278 if ( $this->parallelize
=== 'implicit' ) {
279 if ( !isset( $opts['parallelize'] ) ||
$opts['parallelize'] ) {
280 $opts['concurrency'] = $this->concurrency
;
282 } elseif ( $this->parallelize
=== 'explicit' ) {
283 if ( !empty( $opts['parallelize'] ) ) {
284 $opts['concurrency'] = $this->concurrency
;
287 return $this->doOperationsInternal( $ops, $opts );
291 * @see FileBackend::doOperations()
293 abstract protected function doOperationsInternal( array $ops, array $opts );
296 * Same as doOperations() except it takes a single operation.
297 * If you are doing a batch of operations that should either
298 * all succeed or all fail, then use that function instead.
300 * @see FileBackend::doOperations()
302 * @param $op Array Operation
303 * @param $opts Array Operation options
306 final public function doOperation( array $op, array $opts = array() ) {
307 return $this->doOperations( array( $op ), $opts );
311 * Performs a single create operation.
312 * This sets $params['op'] to 'create' and passes it to doOperation().
314 * @see FileBackend::doOperation()
316 * @param $params Array Operation parameters
317 * @param $opts Array Operation options
320 final public function create( array $params, array $opts = array() ) {
321 return $this->doOperation( array( 'op' => 'create' ) +
$params, $opts );
325 * Performs a single store operation.
326 * This sets $params['op'] to 'store' and passes it to doOperation().
328 * @see FileBackend::doOperation()
330 * @param $params Array Operation parameters
331 * @param $opts Array Operation options
334 final public function store( array $params, array $opts = array() ) {
335 return $this->doOperation( array( 'op' => 'store' ) +
$params, $opts );
339 * Performs a single copy operation.
340 * This sets $params['op'] to 'copy' and passes it to doOperation().
342 * @see FileBackend::doOperation()
344 * @param $params Array Operation parameters
345 * @param $opts Array Operation options
348 final public function copy( array $params, array $opts = array() ) {
349 return $this->doOperation( array( 'op' => 'copy' ) +
$params, $opts );
353 * Performs a single move operation.
354 * This sets $params['op'] to 'move' and passes it to doOperation().
356 * @see FileBackend::doOperation()
358 * @param $params Array Operation parameters
359 * @param $opts Array Operation options
362 final public function move( array $params, array $opts = array() ) {
363 return $this->doOperation( array( 'op' => 'move' ) +
$params, $opts );
367 * Performs a single delete operation.
368 * This sets $params['op'] to 'delete' and passes it to doOperation().
370 * @see FileBackend::doOperation()
372 * @param $params Array Operation parameters
373 * @param $opts Array Operation options
376 final public function delete( array $params, array $opts = array() ) {
377 return $this->doOperation( array( 'op' => 'delete' ) +
$params, $opts );
381 * Perform a set of independent file operations on some files.
383 * This does no locking, nor journaling, and possibly no stat calls.
384 * Any destination files that already exist will be overwritten.
385 * This should *only* be used on non-original files, like cache files.
387 * Supported operations and their parameters:
395 * a) Create a new file in storage with the contents of a string
399 * 'dst' => <storage path>,
400 * 'content' => <string of new file contents>
403 * b) Copy a file system file into storage
407 * 'src' => <file system path>,
408 * 'dst' => <storage path>
411 * c) Copy a file within storage
415 * 'src' => <storage path>,
416 * 'dst' => <storage path>
419 * d) Move a file within storage
423 * 'src' => <storage path>,
424 * 'dst' => <storage path>
427 * e) Delete a file within storage
431 * 'src' => <storage path>,
432 * 'ignoreMissingSource' => <boolean>
435 * f) Do nothing (no-op)
442 * @par Boolean flags for operations (operation-specific):
443 * - ignoreMissingSource : The operation will simply succeed and do
444 * nothing if the source file does not exist.
446 * $opts is an associative of boolean flags, including:
447 * - bypassReadOnly : Allow writes in read-only mode (since 1.20)
450 * This returns a Status, which contains all warnings and fatals that occured
451 * during the operation. The 'failCount', 'successCount', and 'success' members
452 * will reflect each operation attempted for the given files. The status will be
453 * considered "OK" as long as no fatal errors occured.
455 * @param $ops Array Set of operations to execute
456 * @param $opts Array Batch operation options
460 final public function doQuickOperations( array $ops, array $opts = array() ) {
461 if ( empty( $opts['bypassReadOnly'] ) && $this->isReadOnly() ) {
462 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
464 foreach ( $ops as &$op ) {
465 $op['overwrite'] = true; // avoids RTTs in key/value stores
467 return $this->doQuickOperationsInternal( $ops );
471 * @see FileBackend::doQuickOperations()
474 abstract protected function doQuickOperationsInternal( array $ops );
477 * Same as doQuickOperations() except it takes a single operation.
478 * If you are doing a batch of operations, then use that function instead.
480 * @see FileBackend::doQuickOperations()
482 * @param $op Array Operation
486 final public function doQuickOperation( array $op ) {
487 return $this->doQuickOperations( array( $op ) );
491 * Performs a single quick create operation.
492 * This sets $params['op'] to 'create' and passes it to doQuickOperation().
494 * @see FileBackend::doQuickOperation()
496 * @param $params Array Operation parameters
500 final public function quickCreate( array $params ) {
501 return $this->doQuickOperation( array( 'op' => 'create' ) +
$params );
505 * Performs a single quick store operation.
506 * This sets $params['op'] to 'store' and passes it to doQuickOperation().
508 * @see FileBackend::doQuickOperation()
510 * @param $params Array Operation parameters
514 final public function quickStore( array $params ) {
515 return $this->doQuickOperation( array( 'op' => 'store' ) +
$params );
519 * Performs a single quick copy operation.
520 * This sets $params['op'] to 'copy' and passes it to doQuickOperation().
522 * @see FileBackend::doQuickOperation()
524 * @param $params Array Operation parameters
528 final public function quickCopy( array $params ) {
529 return $this->doQuickOperation( array( 'op' => 'copy' ) +
$params );
533 * Performs a single quick move operation.
534 * This sets $params['op'] to 'move' and passes it to doQuickOperation().
536 * @see FileBackend::doQuickOperation()
538 * @param $params Array Operation parameters
542 final public function quickMove( array $params ) {
543 return $this->doQuickOperation( array( 'op' => 'move' ) +
$params );
547 * Performs a single quick delete operation.
548 * This sets $params['op'] to 'delete' and passes it to doQuickOperation().
550 * @see FileBackend::doQuickOperation()
552 * @param $params Array Operation parameters
556 final public function quickDelete( array $params ) {
557 return $this->doQuickOperation( array( 'op' => 'delete' ) +
$params );
561 * Concatenate a list of storage files into a single file system file.
562 * The target path should refer to a file that is already locked or
563 * otherwise safe from modification from other processes. Normally,
564 * the file will be a new temp file, which should be adequate.
566 * @param $params Array Operation parameters
568 * - srcs : ordered source storage paths (e.g. chunk1, chunk2, ...)
569 * - dst : file system path to 0-byte temp file
572 abstract public function concatenate( array $params );
575 * Prepare a storage directory for usage.
576 * This will create any required containers and parent directories.
577 * Backends using key/value stores only need to create the container.
579 * The 'noAccess' and 'noListing' parameters works the same as in secure(),
580 * except they are only applied *if* the directory/container had to be created.
581 * These flags should always be set for directories that have private files.
583 * @param $params Array
585 * - dir : storage directory
586 * - noAccess : try to deny file access (since 1.20)
587 * - noListing : try to deny file listing (since 1.20)
588 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
591 final public function prepare( array $params ) {
592 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
593 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
595 return $this->doPrepare( $params );
599 * @see FileBackend::prepare()
601 abstract protected function doPrepare( array $params );
604 * Take measures to block web access to a storage directory and
605 * the container it belongs to. FS backends might add .htaccess
606 * files whereas key/value store backends might revoke container
607 * access to the storage user representing end-users in web requests.
608 * This is not guaranteed to actually do anything.
610 * @param $params Array
612 * - dir : storage directory
613 * - noAccess : try to deny file access
614 * - noListing : try to deny file listing
615 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
618 final public function secure( array $params ) {
619 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
620 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
622 return $this->doSecure( $params );
626 * @see FileBackend::secure()
628 abstract protected function doSecure( array $params );
631 * Remove measures to block web access to a storage directory and
632 * the container it belongs to. FS backends might remove .htaccess
633 * files whereas key/value store backends might grant container
634 * access to the storage user representing end-users in web requests.
635 * This essentially can undo the result of secure() calls.
637 * @param $params Array
639 * - dir : storage directory
640 * - access : try to allow file access
641 * - listing : try to allow file listing
642 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
646 final public function publish( array $params ) {
647 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
648 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
650 return $this->doPublish( $params );
654 * @see FileBackend::publish()
656 abstract protected function doPublish( array $params );
659 * Delete a storage directory if it is empty.
660 * Backends using key/value stores may do nothing unless the directory
661 * is that of an empty container, in which case it should be deleted.
663 * @param $params Array
665 * - dir : storage directory
666 * - recursive : recursively delete empty subdirectories first (since 1.20)
667 * - bypassReadOnly : allow writes in read-only mode (since 1.20)
670 final public function clean( array $params ) {
671 if ( empty( $params['bypassReadOnly'] ) && $this->isReadOnly() ) {
672 return Status
::newFatal( 'backend-fail-readonly', $this->name
, $this->readOnly
);
674 return $this->doClean( $params );
678 * @see FileBackend::clean()
680 abstract protected function doClean( array $params );
683 * Check if a file exists at a storage path in the backend.
684 * This returns false if only a directory exists at the path.
686 * @param $params Array
688 * - src : source storage path
689 * - latest : use the latest available data
690 * @return bool|null Returns null on failure
692 abstract public function fileExists( array $params );
695 * Get the last-modified timestamp of the file at a storage path.
697 * @param $params Array
699 * - src : source storage path
700 * - latest : use the latest available data
701 * @return string|bool TS_MW timestamp or false on failure
703 abstract public function getFileTimestamp( array $params );
706 * Get the contents of a file at a storage path in the backend.
707 * This should be avoided for potentially large files.
709 * @param $params Array
711 * - src : source storage path
712 * - latest : use the latest available data
713 * @return string|bool Returns false on failure
715 abstract public function getFileContents( array $params );
718 * Get the size (bytes) of a file at a storage path in the backend.
720 * @param $params Array
722 * - src : source storage path
723 * - latest : use the latest available data
724 * @return integer|bool Returns false on failure
726 abstract public function getFileSize( array $params );
729 * Get quick information about a file at a storage path in the backend.
730 * If the file does not exist, then this returns false.
731 * Otherwise, the result is an associative array that includes:
732 * - mtime : the last-modified timestamp (TS_MW)
733 * - size : the file size (bytes)
734 * Additional values may be included for internal use only.
736 * @param $params Array
738 * - src : source storage path
739 * - latest : use the latest available data
740 * @return Array|bool|null Returns null on failure
742 abstract public function getFileStat( array $params );
745 * Get a SHA-1 hash of the file at a storage path in the backend.
747 * @param $params Array
749 * - src : source storage path
750 * - latest : use the latest available data
751 * @return string|bool Hash string or false on failure
753 abstract public function getFileSha1Base36( array $params );
756 * Get the properties of the file at a storage path in the backend.
757 * Returns FSFile::placeholderProps() on failure.
759 * @param $params Array
761 * - src : source storage path
762 * - latest : use the latest available data
765 abstract public function getFileProps( array $params );
768 * Stream the file at a storage path in the backend.
769 * If the file does not exists, a 404 error will be given.
770 * Appropriate HTTP headers (Status, Content-Type, Content-Length)
771 * must be sent if streaming began, while none should be sent otherwise.
772 * Implementations should flush the output buffer before sending data.
774 * @param $params Array
776 * - src : source storage path
777 * - headers : additional HTTP headers to send on success
778 * - latest : use the latest available data
781 abstract public function streamFile( array $params );
784 * Returns a file system file, identical to the file at a storage path.
785 * The file returned is either:
786 * - a) A local copy of the file at a storage path in the backend.
787 * The temporary copy will have the same extension as the source.
788 * - b) An original of the file at a storage path in the backend.
789 * Temporary files may be purged when the file object falls out of scope.
791 * Write operations should *never* be done on this file as some backends
792 * may do internal tracking or may be instances of FileBackendMultiWrite.
793 * In that later case, there are copies of the file that must stay in sync.
794 * Additionally, further calls to this function may return the same file.
796 * @param $params Array
798 * - src : source storage path
799 * - latest : use the latest available data
800 * @return FSFile|null Returns null on failure
802 abstract public function getLocalReference( array $params );
805 * Get a local copy on disk of the file at a storage path in the backend.
806 * The temporary copy will have the same file extension as the source.
807 * Temporary files may be purged when the file object falls out of scope.
809 * @param $params Array
811 * - src : source storage path
812 * - latest : use the latest available data
813 * @return TempFSFile|null Returns null on failure
815 abstract public function getLocalCopy( array $params );
818 * Check if a directory exists at a given storage path.
819 * Backends using key/value stores will check if the path is a
820 * virtual directory, meaning there are files under the given directory.
822 * Storage backends with eventual consistency might return stale data.
824 * @param $params array
826 * - dir : storage directory
827 * @return bool|null Returns null on failure
830 abstract public function directoryExists( array $params );
833 * Get an iterator to list *all* directories under a storage directory.
834 * If the directory is of the form "mwstore://backend/container",
835 * then all directories in the container should be listed.
836 * If the directory is of form "mwstore://backend/container/dir",
837 * then all directories directly under that directory should be listed.
838 * Results should be storage directories relative to the given directory.
840 * Storage backends with eventual consistency might return stale data.
842 * @param $params array
844 * - dir : storage directory
845 * - topOnly : only return direct child dirs of the directory
846 * @return Traversable|Array|null Returns null on failure
849 abstract public function getDirectoryList( array $params );
852 * Same as FileBackend::getDirectoryList() except only lists
853 * directories that are immediately under the given directory.
855 * Storage backends with eventual consistency might return stale data.
857 * @param $params array
859 * - dir : storage directory
860 * @return Traversable|Array|null Returns null on failure
863 final public function getTopDirectoryList( array $params ) {
864 return $this->getDirectoryList( array( 'topOnly' => true ) +
$params );
868 * Get an iterator to list *all* stored files under a storage directory.
869 * If the directory is of the form "mwstore://backend/container",
870 * then all files in the container should be listed.
871 * If the directory is of form "mwstore://backend/container/dir",
872 * then all files under that directory should be listed.
873 * Results should be storage paths relative to the given directory.
875 * Storage backends with eventual consistency might return stale data.
877 * @param $params array
879 * - dir : storage directory
880 * - topOnly : only return direct child files of the directory (since 1.20)
881 * @return Traversable|Array|null Returns null on failure
883 abstract public function getFileList( array $params );
886 * Same as FileBackend::getFileList() except only lists
887 * files that are immediately under the given directory.
889 * Storage backends with eventual consistency might return stale data.
891 * @param $params array
893 * - dir : storage directory
894 * @return Traversable|Array|null Returns null on failure
897 final public function getTopFileList( array $params ) {
898 return $this->getFileList( array( 'topOnly' => true ) +
$params );
902 * Invalidate any in-process file existence and property cache.
903 * If $paths is given, then only the cache for those files will be cleared.
905 * @param $paths Array Storage paths (optional)
908 public function clearCache( array $paths = null ) {}
911 * Lock the files at the given storage paths in the backend.
912 * This will either lock all the files or none (on failure).
914 * Callers should consider using getScopedFileLocks() instead.
916 * @param $paths Array Storage paths
917 * @param $type integer LockManager::LOCK_* constant
920 final public function lockFiles( array $paths, $type ) {
921 return $this->lockManager
->lock( $paths, $type );
925 * Unlock the files at the given storage paths in the backend.
927 * @param $paths Array Storage paths
928 * @param $type integer LockManager::LOCK_* constant
931 final public function unlockFiles( array $paths, $type ) {
932 return $this->lockManager
->unlock( $paths, $type );
936 * Lock the files at the given storage paths in the backend.
937 * This will either lock all the files or none (on failure).
938 * On failure, the status object will be updated with errors.
940 * Once the return value goes out scope, the locks will be released and
941 * the status updated. Unlock fatals will not change the status "OK" value.
943 * @param $paths Array Storage paths
944 * @param $type integer LockManager::LOCK_* constant
945 * @param $status Status Status to update on lock/unlock
946 * @return ScopedLock|null Returns null on failure
948 final public function getScopedFileLocks( array $paths, $type, Status
$status ) {
949 return ScopedLock
::factory( $this->lockManager
, $paths, $type, $status );
953 * Get an array of scoped locks needed for a batch of file operations.
955 * Normally, FileBackend::doOperations() handles locking, unless
956 * the 'nonLocking' param is passed in. This function is useful if you
957 * want the files to be locked for a broader scope than just when the
958 * files are changing. For example, if you need to update DB metadata,
959 * you may want to keep the files locked until finished.
961 * @see FileBackend::doOperations()
963 * @param $ops Array List of file operations to FileBackend::doOperations()
964 * @param $status Status Status to update on lock/unlock
965 * @return Array List of ScopedFileLocks or null values
968 abstract public function getScopedLocksForOps( array $ops, Status
$status );
971 * Get the root storage path of this backend.
972 * All container paths are "subdirectories" of this path.
974 * @return string Storage path
977 final public function getRootStoragePath() {
978 return "mwstore://{$this->name}";
982 * Get the file journal object for this backend
984 * @return FileJournal
986 final public function getJournal() {
987 return $this->fileJournal
;
991 * Check if a given path is a "mwstore://" path.
992 * This does not do any further validation or any existence checks.
994 * @param $path string
997 final public static function isStoragePath( $path ) {
998 return ( strpos( $path, 'mwstore://' ) === 0 );
1002 * Split a storage path into a backend name, a container name,
1003 * and a relative file path. The relative path may be the empty string.
1004 * This does not do any path normalization or traversal checks.
1006 * @param $storagePath string
1007 * @return Array (backend, container, rel object) or (null, null, null)
1009 final public static function splitStoragePath( $storagePath ) {
1010 if ( self
::isStoragePath( $storagePath ) ) {
1011 // Remove the "mwstore://" prefix and split the path
1012 $parts = explode( '/', substr( $storagePath, 10 ), 3 );
1013 if ( count( $parts ) >= 2 && $parts[0] != '' && $parts[1] != '' ) {
1014 if ( count( $parts ) == 3 ) {
1015 return $parts; // e.g. "backend/container/path"
1017 return array( $parts[0], $parts[1], '' ); // e.g. "backend/container"
1021 return array( null, null, null );
1025 * Normalize a storage path by cleaning up directory separators.
1026 * Returns null if the path is not of the format of a valid storage path.
1028 * @param $storagePath string
1029 * @return string|null
1031 final public static function normalizeStoragePath( $storagePath ) {
1032 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1033 if ( $relPath !== null ) { // must be for this backend
1034 $relPath = self
::normalizeContainerPath( $relPath );
1035 if ( $relPath !== null ) {
1036 return ( $relPath != '' )
1037 ?
"mwstore://{$backend}/{$container}/{$relPath}"
1038 : "mwstore://{$backend}/{$container}";
1045 * Get the parent storage directory of a storage path.
1046 * This returns a path like "mwstore://backend/container",
1047 * "mwstore://backend/container/...", or null if there is no parent.
1049 * @param $storagePath string
1050 * @return string|null
1052 final public static function parentStoragePath( $storagePath ) {
1053 $storagePath = dirname( $storagePath );
1054 list( $b, $cont, $rel ) = self
::splitStoragePath( $storagePath );
1055 return ( $rel === null ) ?
null : $storagePath;
1059 * Get the final extension from a storage or FS path
1061 * @param $path string
1064 final public static function extensionFromPath( $path ) {
1065 $i = strrpos( $path, '.' );
1066 return strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1070 * Check if a relative path has no directory traversals
1072 * @param $path string
1076 final public static function isPathTraversalFree( $path ) {
1077 return ( self
::normalizeContainerPath( $path ) !== null );
1081 * Validate and normalize a relative storage path.
1082 * Null is returned if the path involves directory traversal.
1083 * Traversal is insecure for FS backends and broken for others.
1085 * This uses the same traversal protection as Title::secureAndSplit().
1087 * @param $path string Storage path relative to a container
1088 * @return string|null
1090 final protected static function normalizeContainerPath( $path ) {
1091 // Normalize directory separators
1092 $path = strtr( $path, '\\', '/' );
1093 // Collapse any consecutive directory separators
1094 $path = preg_replace( '![/]{2,}!', '/', $path );
1095 // Remove any leading directory separator
1096 $path = ltrim( $path, '/' );
1097 // Use the same traversal protection as Title::secureAndSplit()
1098 if ( strpos( $path, '.' ) !== false ) {
1102 strpos( $path, './' ) === 0 ||
1103 strpos( $path, '../' ) === 0 ||
1104 strpos( $path, '/./' ) !== false ||
1105 strpos( $path, '/../' ) !== false